﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

using ProjectMadaktariMVC.Models;

namespace ProjectMadaktariMVC.Controllers
{
    [Authorize]
    public class PatientController : Controller
    {
        private PatientDAO patientDAO = new PatientDAO();
        private EpisodeDAO episodeDAO = new EpisodeDAO();
        private ProcedureDAO procedureDAO = new ProcedureDAO();

        // HTTP-GET: /Patient/
        public void Index()
        {
            Response.Write("<h1>Hello World</h2>");
        }

        public ActionResult New()
        {
            Patient patient = new Patient();
            return View(patient);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult New(Patient patient)
        {
            try
            {
                patientDAO.Add(patient);
                patientDAO.Save();
                return RedirectToAction("View", new { id = patient.patientID });
            }
            catch
            {
                patientDAO.Delete(patient);
                foreach (var issue in patient.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }

                return View(patient);
            }
        }

        public ActionResult Find()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Find(FormCollection formValues)
        {
            //pulls out string to get.
            string fname = formValues.Get("fname");
            string lname = formValues.Get("lname");
            string cellNumber = formValues.Get("cellNumber");
            string procedureDate = formValues.Get("procedureDate");

            ViewData["fname"] = fname;
            ViewData["lname"] = lname;
            ViewData["cellNumber"] = cellNumber;
            ViewData["procedureDate"] = procedureDate;

            //Send that info to DAO
            //Returns a list of patients

            List<Patient> patientList = patientDAO.FindPatient(fname, lname, cellNumber, procedureDate); //Method to search

            ViewData["patientList"] = patientList;

            return View("FindResults");
        }

        public ActionResult View(int id)
        {
            Patient patient = patientDAO.GetPatient(id);
            return View(patient);
        }

        public ActionResult Edit(int id)
        {
            Patient patient = patientDAO.GetPatient(id);
            return View(patient);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Patient patient = patientDAO.GetPatient(id);

            try
            {

                UpdateModel(patient);

                patientDAO.Save();
                return RedirectToAction("View", new { id = patient.patientID });
            }
            catch
            {
                foreach (var issue in patient.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }

                return View(patient);
            }
        }

        public ActionResult AddEpisode(int id)
        {
            Patient patient = patientDAO.GetPatient(id);

            Episode episode = new Episode();

            ViewData["episode"] = episode;
            ViewData["patientId"] = id;

            return View(patient);

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddEpisode(int id, Episode episode, FormCollection formValues)
        {
            Patient patient = patientDAO.GetPatient(id);
            PopulateEpisode(episode, formValues);
            patient.Episodes.Add(episode);
            patientDAO.Save();

            return Redirect(Url.Action("ViewEpisode", new { patientId = patient.patientID, episodeId = patient.Episodes.Last().episodeID }) + "#" + formValues.Get("tab"));
        }

        public ActionResult EditEpisode(int patientId, int episodeId)
        {
            Patient patient = patientDAO.GetPatient(patientId);
            Episode episode = patient.Episodes.Single(e => e.episodeID == episodeId);
            ViewData["episode"] = episode;
            ViewData["patientId"] = patientId;
            return View(patient);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditEpisode(int patientId, int episodeId, FormCollection formValues)
        {
            Patient patient = patientDAO.GetPatient(patientId);
            Episode episode = episodeDAO.GetEpisode(episodeId);
            PopulateEpisode(episode, formValues);
            patientDAO.Save();

            return Redirect(Url.Action("ViewEpisode", new { patientId = patientId, episodeId = episodeId }) + "#" + formValues.Get("tab"));
        }

        public ActionResult ViewEpisode(int patientId, int episodeId)
        {

            Patient patient = patientDAO.GetPatient(patientId);

            var episode = patient.Episodes.Single(e => e.episodeID == episodeId);
            
            ViewData["episode"] = episode;

            return View(patient);
        }



        public ActionResult AddProcedure(int episodeId)
        {
            Episode episode = episodeDAO.GetEpisode(episodeId);

            ViewData["procedure"] = new Procedure();
            ViewData["episode"] = episode;

            return View(episode);

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddProcedure(int episodeId, Procedure procedure, FormCollection formValues)
        {
            Episode episode = episodeDAO.GetEpisode(episodeId);

            UpdateModel(procedure);
            episode.Procedures.Add(procedure);

            episodeDAO.Save();

            return Redirect(Url.Action("ViewEpisode", new { episodeId = episode.episodeID, patientId = episode.patientID }) + "#Procedure");
        }

        public ActionResult EditProcedure(int procedureId)
        {
            Procedure procedure = procedureDAO.GetProcedure(procedureId);
            ViewData["episode"] = procedure.Episode;
            return View(procedure);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditProcedure(int procedureId, FormCollection formValues)
        {
            Procedure procedure = procedureDAO.GetProcedure(procedureId);
            UpdateModel(procedure);
            procedureDAO.Save();
            return Redirect(Url.Action("ViewEpisode", new { episodeId = procedure.episodeID, patientId = procedure.Episode.patientID }) + "#Procedure");
        }


        private void PopulateEpisode(Episode episode, FormCollection formValues)
        {
            if (formValues.Get("dischargeDate") != null && formValues.Get("dischargeDate").Trim() != "")
                episode.dischargeDate = DateTime.Parse(formValues.Get("dischargeDate"));
            if (formValues.Get("admitDate") != null && formValues.Get("admitDate").Trim() != "")
                episode.admitDate = DateTime.Parse(formValues.Get("admitDate"));
            episode.caseComments = formValues.Get("caseComments");
            episode.complicationNotes = formValues.Get("complicationsNotes");
            if (formValues.Get("complications") != null && formValues.Get("complications").Trim() != "")
                episode.complications = bool.Parse(formValues.Get("complications"));
            if (formValues.Get("followUpDate") != null && formValues.Get("followUpDate").Trim() != "")
                episode.followUpDate = DateTime.Parse(formValues.Get("followUpDate"));
            episode.followUpStatus = formValues.Get("followUpStatus");
            if (formValues.Get("hospitalID") != null && formValues.Get("hospitalID").Trim() != "")
                episode.hospitalID = int.Parse(formValues.Get("hospitalID"));
            episode.imageFindings = formValues.Get("imageFindings");
            episode.postOpStatus = formValues.Get("postOpStatus");
            if (formValues.Get("referalLocationID") != null && formValues.Get("referalLocationID").Trim() != "")
                episode.referalLocationID = int.Parse(formValues.Get("referalLocationID"));
            if (formValues.Get("concomitantDiagnosis1ID") != null && formValues.Get("concomitantDiagnosis1ID").Trim() != "")
                episode.ConcomitantDiagnosi =  ConfigurationDAO.GetConcomitantDiagnosis(int.Parse(formValues.Get("concomitantDiagnosis1ID")));
            if (formValues.Get("concomitantDiagnosis2ID") != null && formValues.Get("concomitantDiagnosis2ID").Trim() != "")
                episode.ConcomitantDiagnosi1 = ConfigurationDAO.GetConcomitantDiagnosis(int.Parse(formValues.Get("concomitantDiagnosis2ID")));
            episode.diagnosisOther = formValues.Get("diagnosisOther");
            var diagnoses = formValues.Get("diagnoses");
            if (diagnoses == null)
            {
                episode.EpisodeDiagnosisRelationships.Clear();
            }
            else
            {
                var newList = diagnoses.Split(',').ToList();
                for (var i = 0; i < episode.EpisodeDiagnosisRelationships.Count; i++ )
                {
                    var rel = episode.EpisodeDiagnosisRelationships.ElementAt(i);
                    if (newList.Contains(rel.diagnosisID.ToString()))
                    {
                        newList.Remove(rel.diagnosisID.ToString());
                    }
                    else
                    {
                        episodeDAO.RemoveEpisodeDiagnosisRelationship(rel);
                    }
                }

                foreach (String s in newList)
                {
                    var dId = int.Parse(s);
                    EpisodeDiagnosisRelationship rel = new EpisodeDiagnosisRelationship();
                    rel.diagnosisID = dId;
                    episode.EpisodeDiagnosisRelationships.Add(rel);
                }
            }
            episode.surgicalHistory = formValues.Get("surgicalHistory");
        }
    }
}
